package com.daiqile.myinterest.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.daiqile.myinterest.R;
import com.daiqile.myinterest.overlayutil.PoiOverlay;
import com.vondear.rxtools.RxBarTool;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class POINearByActivity extends AppCompatActivity implements OnGetPoiSearchResultListener {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.bottomNB)
    BottomNavigationBar bottomNB;
    private PoiSearch mPoiSearch = null;
    private BaiduMap mBaiduMap;
    LatLng myLocation  = new LatLng(29.814056,121.555012);
    double latitude;
    double longitude;

    int radius = 1000;
    int type = 0;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poinear_by);
        ButterKnife.bind(this);
        RxBarTool.setTransparentStatusBar(this);//状态栏透明化

        //搜索
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        //地图
        mBaiduMap = mapView.getMap();
        //定位
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //set BottomNavigationBar
        bottomNB.setMode(BottomNavigationBar.MODE_FIXED)
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_RIPPLE)
                .setActiveColor(R.color.material_white)//在BACKGROUND_STYLE_STATIC 模式下颜色是图标和文字的颜色（选中/未选中），在BACKGROUND_STYLE_RIPPLE 模式下是底部导航栏背景色。
                .setInActiveColor(R.color.material_blueGrey_700)
                .setBarBackgroundColor(R.color.tabtext);//在BACKGROUND_STYLE_STATIC 模式下颜色是底部导航栏背景色，BACKGROUND_STYLE_RIPPLE模式下是图标和文字的颜色（选中/未选中）

        BottomNavigationItem item1 = new BottomNavigationItem(R.drawable.food_s, getString(R.string.restaurant)).setInactiveIconResource(R.drawable.food_n).setActiveColorResource(R.color.material_white);
        BottomNavigationItem item2 = new BottomNavigationItem(R.drawable.bank_s, getString(R.string.bank)).setInactiveIconResource(R.drawable.bank_n).setActiveColorResource(R.color.material_white);
        BottomNavigationItem item3 = new BottomNavigationItem(R.drawable.bus_s, getString(R.string.bus)).setInactiveIconResource(R.drawable.bus_n).setActiveColorResource(R.color.material_white);
        BottomNavigationItem item4 = new BottomNavigationItem(R.drawable.school_s, getString(R.string.school)).setInactiveIconResource(R.drawable.school_n).setActiveColorResource(R.color.material_white);
        bottomNB.addItem(item1)
                .addItem(item2)
                .addItem(item3)
                .addItem(item4)
                .setFirstSelectedPosition(0)
                .initialise();
        bottomNB.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                switch (position){
                    case 0:
                        String restaurant = "餐厅";
                        getSearch(restaurant);
                        break;
                    case 1:
                        String bank = "银行";
                        getSearch(bank);
                        break;
                    case 2:
                        String bus = "公交";
                        getSearch(bus);
                        break;
                    case 3:
                        String school = "学校";
                        getSearch(school);
                        break;
                }
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });

        String restaurant = "餐厅";
        getSearch(restaurant);

    }
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
             latitude = location.getLatitude();    //获取纬度信息
             longitude = location.getLongitude();    //获取经度信息
        }
    }

    @OnClick({R.id.btn_one, R.id.btn_two, R.id.btn_three})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_one:
                String restaurant = "餐厅";
                getSearch(restaurant);
                break;
            case R.id.btn_two:
                String bank = "银行";
                getSearch(bank);
                break;
            case R.id.btn_three:
                String bus = "公交";
                getSearch(bus);
                break;
        }
    }

    private void getSearch(String key) {
        PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption().keyword(key).sortType(PoiSortType.distance_from_near_to_far).location(myLocation)
                .radius(radius).pageNum(1);
        mPoiSearch.searchNearby(nearbySearchOption);
    }


    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(POINearByActivity.this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            mBaiduMap.clear();
            mBaiduMap.hideInfoWindow();
            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(result);
            overlay.addToMap();
            overlay.zoomToSpan();
            BitmapDescriptor centerBitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_mapmark);
            MarkerOptions ooMarker = new MarkerOptions().position(myLocation).icon(centerBitmap);
            mBaiduMap.addOverlay(ooMarker);
            OverlayOptions ooCircle = new CircleOptions().fillColor(Color.argb(100, 135, 206, 235))
                    .center(myLocation).stroke(new Stroke(5, Color.argb(255, 135, 206, 235)))
                    .radius(radius);
            mBaiduMap.addOverlay(ooCircle);
            //创建InfoWindow展示的view
            View infoView = View.inflate(getApplicationContext(), R.layout.item_infowindow, null);
            Button button = new Button(getApplicationContext());
            button.setText("瓜皮");
            button.setTextColor(Color.argb(255, 255, 255, 255));
            button.setBackgroundResource(R.drawable.popup);
            //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
            final InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(infoView), myLocation, -100, new InfoWindow.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick() {
                    //点击InfoWindow隐藏
//                mBaiduMap.hideInfoWindow();
                }
            });
            //显示InfoWindow
            mBaiduMap.showInfoWindow(mInfoWindow);
            type = 0;
            return;
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {
            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : result.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            Toast.makeText(POINearByActivity.this, strInfo, Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult result) {
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(POINearByActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(POINearByActivity.this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            // if (poi.hasCaterDetails) {
            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                    .poiUid(poi.uid));
            // }
            return true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPoiSearch.destroy();
        mapView.onDestroy();
        mBaiduMap = null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }
}
